import { Component, OnInit , ViewChild  } from '@angular/core';
import { CommonService } from '../../service/common.service';
import { StorageService } from '../../service/storage.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-recharge',
  templateUrl: './recharge.page.html',
  styleUrls: ['./recharge.page.scss'],
})
export class RechargePage implements OnInit {

  @ViewChild('avatarInput') avatarInput;

  public num: number;
  public filearr: any[] = [];
  public flag = true;
  public show = false;
  public formData: any;

  constructor(public common: CommonService,public storage: StorageService,private router: Router) {

  }

  ngOnInit() {

  }

  dealImage(base64, w) {
    // var preview = document.getElementById("uploadimg");
    const newImage = new Image();
    let quality = 0.6;    //压缩系数0-1之间
    newImage.src = base64;
    newImage.setAttribute('crossOrigin', 'Anonymous');	//url为外域时需要
    let imgWidth; let imgHeight;
    const that = this;
    newImage.onload = (()=>{
        imgWidth = newImage.width;
        imgHeight = newImage.height;
        // console.log(imgWidth)
        // console.log(imgHeight)
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        if (Math.max(imgWidth, imgHeight) > w) {
            if (imgWidth > imgHeight) {
                canvas.width = w;
                canvas.height = w * imgHeight / imgWidth;
            } else {
                canvas.height = w;
                canvas.width = w * imgWidth / imgHeight;
            }
        } else {
            canvas.width = imgWidth;
            canvas.height = imgHeight;
            quality = 0.6;
        }
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(newImage, 0, 0, canvas.width, canvas.height);
        const base64a = canvas.toDataURL('image/jpeg', quality); //压缩语句
        const newfile =  that.dataURLtoFile(base64a,new Date().getTime()+'.jpeg');
        // console.log(newfile)
        //callback(newfile);//必须通过回调函数返回，否则无法及时拿到该值
        that.formData.append('file',newfile);
        that.aa();
        // console.log(that.formData)
      });
  }
  dataURLtoFile(dataurl, filename) { // base64转file对象
    const arr = dataurl.split(','); const mime = arr[0].match(/:(.*?);/)[1];
        const bstr = atob(arr[1]); let n = bstr.length; const u8arr = new Uint8Array(n);
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, {type:mime});
  }

  onblur(){
    const patrn = /^\d+(\.\d+)?$/;
    if(!patrn.exec(this.num+'')){
      this.common.presentToast('请输入正确的金额');
      this.num = undefined;
    }
  }

  changefile(e){
    this.show = true;
    // 上传文件
    const fileList = this.avatarInput.nativeElement.files[0];
    this.formData = new FormData();
        // console.log(i)
        const reader = new FileReader();
        reader.readAsDataURL(fileList);
        const size = fileList.size;
        const that = this;
        reader.onload = ( (res) =>{
          if(that.filearr.length === 3){
            that.show = false;
            that.common.presentToast('最多上传3张');
            return false;
          }
          if(size > 1024 * 1024){
            // console.log(e.target.result)
            that.dealImage(res.target.result,800);
          }else{
            that.formData.append('file', fileList);
            that.aa();
          }
        });
  }

  aa(){
    // 取消上传图
    const api = '/tbr/uploadImgs';
    // console.log(this.formData.get('file'))
    this.common.postbody(api,this.formData).then((response: any)=>{
      // console.log(response)
      // 加入数组
      if(response.code === 200){
        this.show = false;
          this.filearr.push(response.data[0]);
      }
      console.log(this.filearr);
    });
  }

  changePhoto(e) {
    // 触发上传图片按钮
    this.avatarInput.nativeElement.dispatchEvent(new MouseEvent('click'));
  }

  // 确认充值
  confirm(){
    // this.router.navigate(['/confirmorder/yes'],{
    //   queryParams: {
    //     title:"充值申请提交成功",
    //     coin:this.num,
    //     url:'/home/mymoney/payhistory'
    //   }
    // })
    if(this.num == null){
      this.common.presentAlert('请输入金额');
      return false;
    }
    if(this.num <= 0){
      this.common.presentAlert('请输入正确金额');
      return false;
    }
    if(this.filearr.length === 0){
      this.common.presentAlert('请上传凭证');
      return false;
    }
    this.show = true;
    let path = '';
    for(let i=0;i<this.filearr.length;i++){
      if(i === this.filearr.length-1){
        path += this.filearr[i];
      }else{
        path += this.filearr[i]+',';
      }

    }
    const api='/tbr/offlineRecharge';
    const params = {
      userId:this.storage.get('PersonalInfo').userId,
      balance:this.num.toFixed(2),
      voucherPath:path
    };
    this.common.post(api,params,false).then((res: any)=>{
      console.log(res);
      if(res.code === 200){
        this.show = false;
        this.router.navigate(['/success'],{
          queryParams: {
            title:'充值申请提交成功',
            coin:this.num,
            url:'/tabs/tab3'
          }
        });
      }else{
        this.show = false;
      }
    });

  }




}
